package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;

@WebServlet(name = "RecentQuestionsControllerServlet", urlPatterns = "/RecentQuestionsControllerServlet")
public class RecentQuestionsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3021776680335077472L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String boardId = (String) request.getParameter("boardid");
		int boardIdNumber = Integer.parseInt(boardId);
		int offset = Integer.parseInt(request.getParameter("offset"));

		try {

			Board board = Boards.getBoard(boardIdNumber);
			List<NewAnswersThread> threads = board.getRecentQuestions(offset, 50);

			String userId = null;

			if (request.getUserPrincipal() != null) {
				userId = request.getUserPrincipal().getName();
			}

			User user = User.get(userId);

			if (board.isPrivateBoard() && (!user.isMemberOfBoard(boardIdNumber))) {
				return;
			}

			offset += 50;
			request.setAttribute("board", board);
			request.setAttribute("threads", threads);
			request.setAttribute("userid", userId);
			request.setAttribute("offset", (offset + ""));

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/viewrecentquestions.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}